<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-09-22 09:56:09
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 加料单
 */

namespace App\Http\Services\Finance;


use App\Http\Services\Service;
use App\Repositories\CompanyRepository;
use App\Repositories\FinanceBalanceRepository;
use App\Repositories\SubjectRepository;
use App\Repositories\FinanceVoucherDetailsRepository;
use Illuminate\Support\Facades\DB;

/**
 * @property FinanceBalanceRepository $repository
 * @property SubjectRepository $subject
 * @property FinanceVoucherDetailsRepository $voucher
 * @property CompanyRepository $company
 */
class SummaryService extends Service
    {

    public function boot(
        FinanceBalanceRepository $repository,
        SubjectRepository $subject,
        FinanceVoucherDetailsRepository $voucher,
        CompanyRepository $company
    ) {
        $this->repository = $repository;
        $this->subject    = $subject;
        $this->voucher    = $voucher;
        $this->company    = $company;
        }


    public function browser()
        {
        // SELECT value - LAG(value) OVER (ORDER BY id) AS difference
        // FROM your_table
        $request      = request();
        $prior_amount = $request->prior_amount ?? 0;
        $begindata    = "";

        $data = $this->voucher
            ->select()
            ->addSelect(DB::raw("sum(amount) over(order by code asc)+{$prior_amount}  as amount"))
            ->condition($this->condition($begindata))
            ->getGrid();
        if ($request->page == 1) {
            $data['rows']->prepend([
                'billdate'      => $begindata,
                'summary'       => '期初',
                'amount'        => $prior_amount,
                'debit_amount'  => $request->prior_debit_amount,
                'credit_amount' => $request->prior_credit_amount,
            ]);
            }
        return $data;
        }

    public function companylist()
        {
        $data = $this->company->condition()->with(['category'])
            ->where(function ($query)
                {
                $query->orWhere("debit_amount", ">", 0)
                    ->orWhere("credit_amount", ">", 0)
                    ->orWhere("finance_balance", ">", 0)
                    ->orWhere("debit_invoice_amount", ">", 0)
                    ->orWhere("credit_invoice_amount", ">", 0)
                    ->orWhere("invoice_amount", ">", 0);
                })
            ->getGrid();
        return $data;
        }
    }